import { fetchPayOrder, createPaidVipOrder } from '../services/vipService';
import { Toast } from 'antd-mobile';

function doWxJsPay(data) {
  const { shopId, openid, cardType, mobile, branchId } = data;
  return new Promise((resolve, reject) => {
    createPaidVipOrder(shopId, {
      mobile,
      openid,
      branchId,
      cardType,
    }).then((res) => {
      if (res && res.data) {
        if (res.data.noNeedToPay) {
          resolve({ success: true });
        } else if (res.data.error) {
          Toast.fail(res.data.message);
        } else if (res.data.orderId && res.data.payParams) {
          callWxJsPay(res.data.payParams, (result) => {
            if (result) {
              confirmOrderStatus(res.data.orderId).then(() => {
                resolve({ success: true });
              }).catch((error) => {
                console.error('confirmOrderStatus', { error });
                resolve();
              });
            } else {
              resolve();
            }
          });
        } else {
          resolve();
        }
      }
    }).catch((error) => {
      const msg = error.message || '未知错误';
      resolve({ success: false, message: msg });
    });
  });
}

function callWxJsPay(data, callback) {
  const { appId, timeStamp, nonceStr, signType, paySign } = data;
  function onBridgeReady() {
    WeixinJSBridge.invoke(
      'getBrandWCPayRequest', {
        appId,
        timeStamp,
        nonceStr,
        package: data.package,
        signType,
        paySign,
      },
      (res) => {
        console.log('getBrandWCPayRequest result', { res });
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          // 使用以上方式判断前端返回,微信团队郑重提示：
          //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          callback(true);
        } else {
          callback();
        }
      });
  }
  if (typeof WeixinJSBridge == "undefined") {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
      document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
    }
  } else {
    onBridgeReady();
  }
}

function confirmOrderStatus(orderId, intervalMs = 2500, times = 10) {
  Toast.loading('确认支付中...', intervalMs * times);
  return new Promise((resolve, reject) => {
    let count = 0;
    const timer = setInterval(() => {
      fetchPayOrder(orderId).then((res) => {
        if (res.data && res.data.status == 2) {
          clearInterval(timer);
          Toast.hide();
          resolve(true);
        }
      }).catch((error) => {
        clearInterval(timer);
        console.error('confirmOrderStatus', error);
        reject(error);
      });
      count++;
      if (count >= times) {
        clearInterval(timer);
      }
    }, intervalMs);
  });
}

// function processPaidVipOrder(data) {
//   const { shopId, mobile, cardType } = data;

//   return fetchSyncOnline(shopId).then((res) => {
//     const result = res.data[0];
//     if (result && result.status == 'online') {
//       return fetchPayOrderList({
//         shopId,
//         userId: mobile,
//         productId: 'paid_vip',
//         status: 2,
//         userCardType: cardType,
//       }).then((listRes) => {
//         const listResult = listRes.data;
//         if (listResult.length > 0) {
//           Toast.success('付费会员已支付');
//         } else {
//           return doWxJsPay(data);
//         }
//       });
//     }
//     Toast.fail('同步端未开启');
//   });
// }

export default {
  doWxJsPay,
};
